package com.group3.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.group3.dao.StudentMapper;
import com.group3.domain.Student;
import com.group3.domain.StudentExample;
import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import com.group3.pojo.UpdatePassword;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import com.group3.service.StudentService;
import com.group3.utils.JWTUtils;
import com.group3.utils.Md5;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * StudentServiceImpl
 * 学生业务，修改密码
 *
 * @author WenhaoChen
 * 2021/06/10 16:56
 **/
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;

    /**
     * 修改登录学生的密码
     * @param updatePassword
     * @param token
     * @return
     */
    @Override
    public Result putPassword(UpdatePassword updatePassword, String token) {
        updatePassword.setPassword(Md5.encodeByMD5(updatePassword.getPassword()));//为获取到的密码加密
        updatePassword.setNewPassword(Md5.encodeByMD5(updatePassword.getNewPassword()));

        DecodedJWT jwt = JWTUtils.getToken(token);//获取token
        String studentId = jwt.getClaim("id").asString();//获取登录学生的id

        Student student = new Student();
        student.setStudentId(studentId);
        student.setPassword(updatePassword.getNewPassword());

        StudentExample studentExample = new StudentExample();
        studentExample
                .createCriteria()
                .andStudentIdEqualTo(studentId)
                .andPasswordEqualTo(updatePassword.getPassword());//添加查询条件

        if (studentMapper.selectByExample(studentExample).isEmpty()) {//查询结果为空即原密码错误
            throw new BusinessException(ExceptionEnum.OLD_PASSWORD_ERR);//抛出原密码错误异常
        } else {
            int result = studentMapper.updateByPrimaryKeySelective(student);//更新密码操作结果
            if (result > 0) {
                return ResultUtil.success();//返回成功信息
            } else{
                throw new BusinessException(ExceptionEnum.ERROR);
            }
        }
    }


}
